* Imports the data from Statistik Austria
foreach group in 0_14 15_29 30_44 45_59 60_74 75_99 ahs bhs bms bms_bhs uni lehre pflichtschule foreign {
	tempfile `group'
	import delimited "$raw/pop_`group'.csv", encoding(UTF-8) parselocale(en_AT) groupseparator(.) decimalseparator(,) clear
	
	capture replace pop_`group' = "0" if pop_`group'=="-"
	capture replace sh_pop_`group' = "0" if sh_pop_`group'=="-"

	capture destring pop_`group', replace ignore(".")
	capture destring sh_pop_`group', replace dpcomma
		
	* Change in municipal boundaries due to dissolution of the municipality of Murfeld 
	replace municipality_id = 61060 if municipality_id==61056 // St. Veit in der Südsteiermark
	replace municipality_id = 61061 if municipality_id==61058 // Straß in der Steiermark
	drop if municipality_id==62347 // Murfeld
	
	save ``group''
}

use `0_14', clear
foreach group in 15_29 30_44 45_59 60_74 75_99 ahs bhs bms bms_bhs uni lehre pflichtschule foreign {
	merge 1:1 municipality_id using ``group'', nogen
}

save "$edited/pop_statistics", replace

* Import age 5 years - additional data from Statcube 1.1.2021
import delimited "$raw/pop_5_01012021.csv", encoding(UTF-8) decimalseparator(,) clear

gen municipality_id = substr(alterin5jahresgruppen,-6,5)
destring municipality_id, replace
drop *anmerkungen* v?? alterin*

destring pop_*, replace ignore("-")
recode pop_* (.=0)

egen pop = rowtotal(pop_0_4-pop_95_99)

drop if pop==0

foreach var of varlist pop_0_4-pop_75_99 {
	gen sh_`var' = 100 * `var'/pop
}

save "$edited/pop_5_years", replace

* Import by sex - additional data from Statcube 1.1.2021
import delimited "$raw/pop_sex_01012021.csv", encoding(UTF-8) decimalseparator(,) clear varnames(1)

gen municipality_id = substr(gemeinde,-6,5)
destring municipality_id, replace force
*drop werte gemeinde* anmerkungen v7

destring männlich weiblich, replace ignore("-")
drop if weiblich==. | municipality_id==.

*reshape wide anzahl, i(municipality_id) j(geschlecht) string

gen sh_pop_female = 100* weiblich/(weiblich+männlich)
keep municipality_id sh_pop_female

save "$edited/pop_female", replace

* Import urban-rural type
import delimited "$raw/urban_rural.csv", encoding(UTF-8) clear

lab define l_urban 1 "densely populated" 2 "intermediate density" 3 "rural"
lab val type_urban_rural l_urban
lab var type_urban_rural "Type of municipality"

save "$edited/urban_rural", replace

* Import urban-rural detailed  type
import delimited "$raw/urban_rural_detailed.csv", encoding(UTF-8) clear
* potentially label values
save "$edited/urban_rural_detailed", replace

* Import income
import delimited "$raw/salaries.csv", encoding(UTF-8) decimalseparator(,) clear
replace salaries = salaries * 1000
save "$edited/salaries", replace

import delimited "$raw/pensions.csv", encoding(UTF-8) decimalseparator(,) clear
replace pensions = pensions * 1000

save "$edited/pensions", replace